var globalObj = globalObj || {};
globalObj = $.extend(globalObj, {
    url: baseUrl + "web/unifyapi",
    alert: function (msg, callback) {
        var _alert = layer.alert(msg, function(index){
            callback && callback(index);
        });
        return _alert;
    },
    tips: function (msg, time, callback) {
        layer.msg(msg || "", {
            time: time || 2000
        }, function(){
            callback && callback();
        });
    },
    flexiblePx: function (content) {
        var _dpr = lib.flexible.dpr;
        var _con = content.replace(/(\d+(\.\d+)?)px/g, function (str) {
            str = str.replace('px', '');
            var value = parseInt(str) * _dpr;
            return value + "px";
        });
        _con = _con.replace(/(\d+(\.\d+)?)pt/g, function (str) {
            str = str.replace('pt', '');
            var value = parseInt(str) * _dpr;
            return value + "px";
        });
        return _con;
    },
    responseConfig: {
        //响应代码
        code: "respCode",
        //响应数据
        data: "param",
        // 页码，每页条数，总条数
        pageData: 'pageParams',
        //错误提示信息
        msg: "respMsg",
        //响应是否是成功的
        isOK: function (response) {
            return (response instanceof Object) && response['respCode'] == "000000";
        }
    },
    /*****
     * Created with WebStorm.
     * Date : 2017/11/9.
     * Author : Ztr.
     * Func : 使用说明↓↓↓↓↓↓↓↓↓↓
     * (new Request('ctrl/action'))
     * .setParams({'post_param':'a post param'})
     * .setGetParams({'get_param':'a get param'})
     * .parse(function(data){
     *  data.total = data.record_count;
     * })
     * .do([data,method])
     * .success(function(data){
     * })
     * .error(function(){
     * });
     ******/
    Request: function (url) {
        var _this = this;
        this._url = url;
        this._param = {
            get: {
            },
            post: {
                appId:"eeda14c1ff8d11853e11698a8abe9977",
                sign:"58E40DCEA527333B9E7C3CCD1A08979F",
                signType:"MD5",
                encryptType:"DES",
                termType: 'WEB_PORTAL',
                sessionId: sessionStorage.getItem('sessionId') || "",
                timestamp: ""+new Date().getTime()
            }
        };
        this._method = 'POST';
        //this._contentType = 'application/x-www-form-urlencoded';
        this._contentType = 'application/json;charset=UTF-8';
        //this._mask = true;
        /**************
         * 是否加请求loading
         */
        this.setMask = function (mask) {
            _this._mask = mask;
            return _this;
        }
        /******
         * 数据转换流
         *******/
        this._parse = [];
        /*******
         * 注册一个数据转换
         *******/
        this.parse = function (fn) {
            _this._parse.push(fn);
            return _this;
        };
        /*******
         * 格式化对应的键值
         * @param k
         * @param v
         *******/
        this.parseSelectArray = function (k, v) {
            var _this = this;
            var _key = k || 'id';
            var _value = v || 'name';
            this.parse(function (data) {
                _this.data = [];
                for (var i = 0; i < data.length; i++) {
                    var _item = data[i];
                    _this.data.push([_item[_key], _item[_value]]);
                }
            });
            return _this;
        };
        /*******
         * 成功回调函数
         *******/
        this._success = null;
        this.success = function (fn) {
            _this._success = fn;
            return _this;
        };
        /*******
         * 请求失败回调函数
         *******/
        this._error = null;
        this.error = function (fn) {
            _this._error = fn;
            return _this;
        };
        /**
         * 默认处理错误回调
         * @param a
         * @param b
         */
        this.__error = function (a, b) {
            var msg = '访问服务器超时，请重试，谢谢！';
            var _code = a[globalObj.responseConfig.code] || '';
            if (a && typeof b == 'undefined') {
                if (a instanceof Object) {
                    if (globalObj.responseConfig.msg instanceof Function) {
                        msg = globalObj.responseConfig.msg(a, b);
                    } else {
                        msg = a[globalObj.responseConfig.msg] || '';
                        if (msg instanceof Object || msg.toString().length < 3) {
                            msg = '访问服务器超时，请重试，谢谢！';
                        }
                    }
                }
            }
             globalObj.alert(msg, function (index) {
                 layer.close(index);
             });
        };

        /**
         * 扩展POST参数
         * @param data
         */
        this.setParams = function (data) {
            $.extend(_this._param.post, data);

            return _this;
        };

        /**
         * 扩展GET参数
         * @param data
         */
        this.setGetParams = function (data) {
            $.extend(_this._param.get, data);
            return _this;
        };

        /**
         * 设置ajax请求方式
         * @param method
         */
        this.setMethod = function (method) {
            this._method = method;
            return _this;
        };

        /**
         * 设置ajax请求的内容编码类型
         * @type {jQuery|HTMLElement}
         */
        this.setContentType = function (contentType) {
            var map = {"json": "application/json"};
            this._contentType = map[contentType] || contentType;
            return this;
        };

        /**
         * 发起请求前执行回调
         */
        this._beforeRequest = null;
        this.beforeRequest = function (fn) {
            this._beforeRequest = fn;
            return this;
        };
        /**
         * 获取完整的数据地址加get请求参数
         * @returns {*}
         */
        this.getUrl = function (data) {
            data = data || {};
            var p = '';
            for (var i in data) {
                p += i + "=" + encodeURIComponent(data[i]) + "&";
            }
            if (p.length > 0) {
                p = (this._url.indexOf('?') > 0 ? "&" : "?") + p.substr(0, p.length - 1);
            }
            return this._url + p;
        }
        /**
         * 执行数据请求data请求参数；method请求方式：post/get
         * @param data
         * @param method
         */
        this.do = function (data, method) {
            if (_this._beforeRequest) {
                _this._beforeRequest(data);
            }
            if (_this._mask) {
                _this._mask = layer.load(1, {
                    shadeClose: false
                });
            }
            method = method || _this._method;
            data = data || {};
            var url = '';
            var _data = {};
            //组装请求数据
            if (method.toUpperCase() == 'GET') {
                $.extend(data, this._param.post);
                url = this.getUrl($.extend({"_yhAjax": (new Date().getTime())}, this._param.get, data));
            } else {
                $.extend(_data, this._param.post, data);
                url = this.getUrl($.extend({"_yhAjax": (new Date().getTime())}, this._param.get));
            }
            $.ajax({
                type: method,
                url: url,
                data: JSON.stringify(_data),
                contentType: _this._contentType,
                dataType: 'json',
                timeout: 60 * 1000,
                success: function (rs) {
                    if (_this._mask || _this._mask == 0) {
                        layer.close(_this._mask);
                    }
                    if (!globalObj.responseConfig.isOK(rs)) {
                        setTimeout(function () {
                            if (!(_this._error instanceof Function) || _this._error(rs) !== false) {
                                _this.__error(rs);
                            }
                        }, 200);
                        return false;
                    }
                    //格式化数据
                    var rawData = rs[globalObj.responseConfig.data];
                    var pageData = rs[globalObj.responseConfig.pageData];
                    var data = null;
                    if (rawData instanceof Object) {
                        data = rawData instanceof Array ? [] : {};
                        $.extend(data, rawData);
                        for (var i = 0; i < _this._parse.length; i++) {
                            if (!(_this._parse[i] instanceof Function) || _this._parse[i].call(_this, data, rawData) !== false) {
                                continue;
                            }
                            break;
                        }
                    } else {
                        data = rawData;

                    }
                    //成功执行回调
                    if (_this._success instanceof Function) {
                        if(pageData){
                            _this._success(data, rawData, pageData);
                        }else{
                            _this._success(data, rawData);
                        }

                    }
                },
                error: function (a, b, c) {
                    if (_this._mask || _this._mask == 0) {
                        layer.close(_this._mask);
                    }
                    setTimeout(function () {
                        if (!(_this._error instanceof Function) || _this._error(a, b, c) !== false) {
                            _this._error = null;
                            _this.__error(a, b, c);
                        }
                    }, 200);
                }
            });
            return _this;
        };
    },
    /*
     * 获取cookie值
     * @name:字符串
     */
    getCookie: function (name) {
        var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
        if (arr = document.cookie.match(reg)) {
            return arr[2];
        } else {
            return null;
        }
    },
    /*
     * 验证函数
     */
    check: {
        /*
         * 验证输入是否空值
         * @val:要验证的字符串
         */
        isNull: function (val) {
            return (val.replace(/\s+/g, "") === "");
        },
        /*
         * 验证输入是否是合法邮箱地址
         * @val:字符串
         */
        isEmail: function (val) {
            var p = /^\w+(?:[-+.']\w+)*@\w+(?:[-.]\w+)*\.\w+(?:[-.]\w+)*$/;
            return p.test(val);
        },
        /*
         * 验证输入是否是合法座机号
         * @val:字符串
         */
        isTelphone: function (val) {
            var p = /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/;
            return p.test(val);
        },
        /*
         * 验证输入是否是合法手机号
         * @val:字符串
         */
        isMobile: function (val) {
            var p = /^[1][0-9]{10}$/;
            return p.test(val);
        },
        /*
         * 字符串长度验证
         * @val:字符串
         * @long:字符串长度
         */
        isHowLong: function (val, long) {
            if (val.length > long) {
                return false;
            } else {
                return true;
            }
        },
        /*
         * 验证输入是否是合法身份证号
         * @val:字符串
         */
        isIDCard: function (val) {
            var p = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
            return p.test(val);
        },
        /*
         * 验证输入是否是数字
         * @val:要验证的字符串或数字
         * @options:可选参数，{min:最小值,max:最大值,decimals:可以带几位小数}
         */
        isNum: function (val, options) {
            var options = options || {};
            var p = /^\d+(?:\.\d+)?$/;
            if (options.decimals) {
                p = new RegExp("^\\d+(?:\\.\\d{1," + options.decimals + "})?$");
            } else if (options.decimals === 0) {
                p = /^\d+$/;
            }
            var test = p.test(val);
            if (options.min) {
                if (parseFloat(val) < options.min) {
                    test = false;
                }
            }
            if (options.max) {
                if (parseFloat(val) > options.max) {
                    test = false;
                }
            }
            return test;
        },
        /*
         * 验证输入是否是合法url地址
         * @val:字符串
         */
        isUrl: function (val) {
            var p = /^(?:http(?:s)?:\/\/)?([\w-]+\.)+[\w-]+(?:\/[\w- .\/\?%&=]*)?$/;
            if (p.test(val)) {
                return true;
            } else {
                return false;
            }
        }
    }
});
//数组indexOf
if (!Array.indexOf) {
    Array.prototype.indexOf = function (val) {
        for (var i = 0, n = this.length; i < n; i++) {
            if (this[i] === val) {
                return i;
            }
        }
        return -1;
    }
}
//格式化日期
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")   ==> 2006-7-2 8:9:4.18
Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

template.helper('dateFormatLong', function (date, format) {
    var str2;
    if (date.length == 6) {
        str2 = date.substr(0, 4) + "年" + date.substr(4, 2) + "月";
    }
    if (date.length >= 8) {
        str2 = date.substr(0, 4) + "年" + date.substr(4, 2) + "月" + date.substr(6, 2) + "日 ";
    }
    if (date.length >= 14) {
        str2 = str2 + date.substr(8, 2) + ":" + date.substr(10, 2) + ":" + date.substr(12, 2);
    }
    return str2;
});
template.helper('dateFormat', function (date, format) {
    var str2;
    if (date.length >= 8) {
        str2 = date.substr(0, 4) + "/" + date.substr(4, 2) + "/" + date.substr(6, 2) + "";
    }
    return str2;
});

template.helper('dateBill', function (date, format) {
    var str2;
    if (date.length >= 8) {
        str2 = date.substr(4, 2) + "/" + date.substr(6, 2) + " ";
    }
    if (date.length >= 14) {
        str2 = str2 + date.substr(8, 2) + ":" + date.substr(10, 2);
    }
    return str2;
});

template.helper('dateRecord', function (date, format) {
    var str2;
    if (date.length >= 8) {
        str2 = date.substr(4, 2) + "月" + date.substr(6, 2) + "日 ";
    }
    if (date.length >= 14) {
        str2 = str2 + date.substr(8, 2) + ":" + date.substr(10, 2);
    }
    return str2;
});
